<template>
  <div class="orders-container">
    <div class="orders-header">
      <h2>我的订单</h2>
    </div>
    
    <!-- 订单状态筛选 -->
    <div class="order-filters">
      <button
        v-for="status in orderStatuses"
        :key="status.value"
        class="filter-button"
        :class="{ 'active': currentStatus === status.value }"
        @click="filterByStatus(status.value)"
      >
        {{ status.label }}
        <span v-if="status.value === 'pending' && userStore.pendingOrders.length > 0" class="status-badge">
          {{ userStore.pendingOrders.length }}
        </span>
      </button>
    </div>
    
    <!-- 订单列表 -->
    <div class="orders-list">
      <div v-if="isLoading" class="loading-state">加载中...</div>
      
      <div v-else-if="filteredOrders.length === 0" class="empty-state">
        <div class="empty-icon">📦</div>
        <p>暂无{{ currentStatusText }}订单</p>
        <router-link to="/" class="go-shopping-button">去购物</router-link>
      </div>
      
      <div v-else>
        <div v-for="order in filteredOrders" :key="order.id" class="order-item">
          <div class="order-header">
            <div class="order-info">
              <span class="order-id">订单编号: {{ order.id }}</span>
              <span class="order-date">{{ formatDate(order.date) }}</span>
            </div>
            <span class="order-status" :class="getOrderStatusClass(order.status)">
              {{ getOrderStatusText(order.status) }}
            </span>
          </div>
          
          <!-- 订单商品列表 -->
          <div class="order-items">
            <div v-for="item in order.items" :key="item.id" class="order-product">
              <div class="product-image">
                <!-- 这里应该显示商品图片，现在用占位符 -->
                <div class="product-placeholder"></div>
              </div>
              <div class="product-info">
                <h4 class="product-name">{{ item.name }}</h4>
                <div class="product-details">
                  <span class="product-price">¥{{ item.price.toFixed(2) }}</span>
                  <span class="product-quantity">x{{ item.quantity }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 订单总计和操作 -->
          <div class="order-footer">
            <div class="order-total">
              共{{ order.items.reduce((sum, item) => sum + item.quantity, 0) }}件商品 合计：
              <span class="total-price">¥{{ order.totalAmount.toFixed(2) }}</span>
            </div>
            <div class="order-actions">
              <button v-if="order.status === 'pending'" class="action-button pay-button" @click="handlePay(order.id)">
                立即支付
              </button>
              <button v-if="order.status === 'pending'" class="action-button cancel-button" @click="handleCancel(order.id)">
                取消订单
              </button>
              <button v-if="order.status === 'completed'" class="action-button review-button" @click="handleReview(order.id)">
                评价晒单
              </button>
              <button class="action-button detail-button" @click="handleDetail(order.id)">
                查看详情
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 分页控件 -->
    <div v-if="filteredOrders.length > 0" class="pagination">
      <button class="pagination-button" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">
        上一页
      </button>
      <span class="pagination-info">
        第 {{ currentPage }} / {{ totalPages }} 页，共 {{ filteredOrders.length }} 条记录
      </span>
      <button class="pagination-button" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()

const isLoading = ref(false)
const currentStatus = ref('all') // 'all', 'pending', 'completed', 'canceled'
const currentPage = ref(1)
const pageSize = 10

// 订单状态选项
const orderStatuses = [
  { label: '全部订单', value: 'all' },
  { label: '待付款', value: 'pending' },
  { label: '已完成', value: 'completed' },
  { label: '已取消', value: 'canceled' }
]

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'completed': '已完成',
    'canceled': '已取消'
  }
  return statusMap[status] || status
}

// 获取订单状态样式类
const getOrderStatusClass = (status) => {
  const statusClassMap = {
    'pending': 'status-pending',
    'completed': 'status-completed',
    'canceled': 'status-canceled'
  }
  return statusClassMap[status] || ''
}

// 获取当前状态文本
const currentStatusText = computed(() => {
  const status = orderStatuses.find(s => s.value === currentStatus.value)
  return status ? status.label : ''
})

// 筛选订单
const filteredOrders = computed(() => {
  if (currentStatus.value === 'all') {
    return userStore.orders
  }
  return userStore.orders.filter(order => order.status === currentStatus.value)
})

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(filteredOrders.value.length / pageSize)
})

// 切换状态筛选
const filterByStatus = (status) => {
  currentStatus.value = status
  currentPage.value = 1
}

// 切换分页
const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 处理支付
const handlePay = (orderId) => {
  alert(`订单${orderId}支付功能待实现`)
}

// 处理取消订单
const handleCancel = (orderId) => {
  if (confirm('确定要取消该订单吗？')) {
    // 这里应该调用API取消订单
    alert(`订单${orderId}已取消`)
  }
}

// 处理评价
const handleReview = (orderId) => {
  alert(`订单${orderId}评价功能待实现`)
}

// 查看订单详情
const handleDetail = (orderId) => {
  alert(`查看订单${orderId}详情功能待实现`)
}

// 加载订单数据
const loadOrders = async () => {
  isLoading.value = true
  try {
    await userStore.fetchOrders()
  } catch (error) {
    console.error('加载订单失败:', error)
    alert('加载订单失败，请稍后重试')
  } finally {
    isLoading.value = false
  }
}

// 组件挂载时加载订单数据
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.orders-container {
  padding: 32px;
}

.orders-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.orders-header h2 {
  margin: 0;
  font-size: 22px;
  color: #333;
}

/* 订单筛选 */
.order-filters {
  display: flex;
  gap: 12px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}

.filter-button {
  padding: 8px 20px;
  background-color: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.filter-button:hover {
  background-color: #e0e0e0;
  color: #333;
}

.filter-button.active {
  background-color: #4285f4;
  color: white;
}

.status-badge {
  position: absolute;
  top: -6px;
  right: -6px;
  background-color: #d32f2f;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 16px;
  text-align: center;
}

/* 订单列表 */
.orders-list {
  margin-bottom: 24px;
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0 0 20px 0;
  font-size: 16px;
}

.go-shopping-button {
  display: inline-block;
  padding: 10px 24px;
  background-color: #4285f4;
  color: white;
  text-decoration: none;
  border-radius: 6px;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.go-shopping-button:hover {
  background-color: #3367d6;
}

/* 订单项 */
.order-item {
  border: 1px solid #eee;
  border-radius: 12px;
  margin-bottom: 20px;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  gap: 20px;
}

.order-id,
.order-date {
  font-size: 14px;
  color: #666;
}

.order-status {
  font-size: 14px;
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 16px;
}

.status-pending {
  background-color: #fff3e0;
  color: #f57c00;
}

.status-completed {
  background-color: #e8f5e8;
  color: #388e3c;
}

.status-canceled {
  background-color: #f5f5f5;
  color: #757575;
}

/* 订单商品 */
.order-items {
  padding: 20px 24px;
}

.order-product {
  display: flex;
  gap: 16px;
  padding: 16px 0;
  border-bottom: 1px solid #eee;
}

.order-product:last-child {
  border-bottom: none;
}

.product-image {
  width: 80px;
  height: 80px;
  background-color: #f5f5f5;
  border-radius: 8px;
  flex-shrink: 0;
}

.product-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f0f0f0;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.product-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  font-size: 16px;
  font-weight: 600;
  color: #d32f2f;
}

.product-quantity {
  font-size: 14px;
  color: #666;
}

/* 订单底部 */
.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background-color: #fafafa;
  border-top: 1px solid #eee;
}

.order-total {
  font-size: 16px;
  color: #666;
}

.total-price {
  font-size: 18px;
  font-weight: 600;
  color: #d32f2f;
  margin-left: 8px;
}

.order-actions {
  display: flex;
  gap: 12px;
}

.action-button {
  padding: 8px 20px;
  border: 1px solid #ddd;
  background-color: white;
  color: #666;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-button:hover {
  border-color: #4285f4;
  color: #4285f4;
}

.pay-button {
  background-color: #4285f4;
  color: white;
  border-color: #4285f4;
}

.pay-button:hover {
  background-color: #3367d6;
  border-color: #3367d6;
  color: white;
}

.cancel-button {
  border-color: #d32f2f;
  color: #d32f2f;
}

.cancel-button:hover {
  background-color: #fee;
  border-color: #d32f2f;
  color: #d32f2f;
}

.review-button {
  border-color: #f57c00;
  color: #f57c00;
}

.review-button:hover {
  background-color: #fff3e0;
  border-color: #f57c00;
  color: #f57c00;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  padding: 20px 0;
}

.pagination-button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background-color: white;
  color: #666;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.pagination-button:hover:not(:disabled) {
  border-color: #4285f4;
  color: #4285f4;
}

.pagination-button:disabled {
  background-color: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.pagination-info {
  font-size: 14px;
  color: #666;
}

@media (max-width: 768px) {
  .orders-container {
    padding: 20px;
  }
  
  .order-filters {
    justify-content: center;
  }
  
  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .order-info {
    flex-direction: column;
    gap: 4px;
  }
  
  .order-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .order-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .pagination {
    flex-direction: column;
    gap: 12px;
  }
}
</style>